import React from 'react';
import { Form, Input, message, Button } from 'antd';
import Api from 'Utils/api';
import * as routerActions from 'react-router-redux';
import { connect } from 'react-redux';
import QuestionOption from './Component/QuestionOption';
import CommonBorder from './../../../../DispatchPage/Components/CommonBorder';


const FormItem = Form.Item;
const { TextArea } = Input;
const CHARACTER_ARR = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
class ModifyQuestion extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      id: props.params.id,
      data: {},
      optionArr: [],
      loading: false
    };
  }
  componentWillMount() {
    this.initData();
  }
  initData() {
    const api = new Api({
      method: 'GET',
      path: `/choices/admin/subject/${this.state.id}`,
      success: (json) => {
        const { optionArr } = this.state;
        const options = json.all_option;
        const answer = json.answer;
        for (let i = 0, len = options.length; i < len; i++) {
          let item = {}; let flag = true;
          // 是否是答案
          for (let j = 0, awLen = answer.length; j < awLen; j++) {
            if (answer[j] === CHARACTER_ARR[i]) {
              flag = false;
              item = {
                sigOption: options[i],
                sigCheck: true
              };
            }
          }
          if (flag) {
            item = {
              sigOption: options[i],
              sigCheck: false
            };
          }
          optionArr.push(item);
        }
        this.setState({ data: json, optionArr: [...optionArr] });
      },
      error: (msg) => {
        message.error(msg, 3);
      },
    });
    api.run();
  }
  handleCancel() {
    this.props.dispatch(routerActions.goBack());
  }
  handleSubmit() {
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const formValue = this.props.form.getFieldsValue();
        // get option component value
        const objValue = Object.values(formValue);
        objValue.shift();
        const allOption = [];
        const selectAnswer = [];
        // get option value arr and answer value arr
        for (let i = 0, len = objValue.length; i < len; i++) {
          allOption.push(objValue[i].sigOption);
          selectAnswer.push(objValue[i].sigCheck);
        }
        // if have a right answer
        if (!(selectAnswer.filter(item => item).length)) {
          message.warn('请设置正确答案', 3);
          return;
        }
        const answer = [];
        for (let i = 0, len = selectAnswer.length; i < len; i++) {
          if (selectAnswer[i]) {
            answer.push(CHARACTER_ARR[i]);
          }
        }
        this.setState({ loading: true });
        const data = {
          question: formValue.question,
          all_option: allOption,
          answer: answer,
        };
        const api = new Api({
          method: 'PATCH',
          path: `/choices/admin/${this.state.id}`,
          data,
          success: () => {
            this.setState({ loading: false });
            this.props.dispatch(routerActions.goBack());
          },
          error: (msg) => {
            message.error(msg, 3);
          },
        });
        api.run();
      }
    });
  }
  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const { data, optionArr } = this.state;
    return (
      <div>
        <CommonBorder
          title="修改问题"
          content={
            <div className="add-new-question-page">
              <Form layout={'horizontal'} className="report-form" >
                <FormItem label="题面">
                  {getFieldDecorator('question', {
                    rules: [
                      { required: true, message: '请输入题面' }
                    ],
                    initialValue: data ? data.question : '',
                  })(
                    <TextArea placeholder="请输入题面" rows={4} style={{ width: 840, height: 150 }} />
                  )}
                </FormItem>
                {
                  /* eslint-disable */
                  optionArr && optionArr.length > 0 ?
                    optionArr.map((item, index) => (
                      <FormItem label={`备选项${index + 1}`} key={index}>
                        {getFieldDecorator(`option${index + 1}`, {
                          initialValue: item
                        })(
                          <QuestionOption />
                        )}
                      </FormItem>
                    ))
                    : ''
                  /* eslint-enable */
                }
              </Form>
              <div className="btn-wrap">
                <Button className="cancel-btn" onClick={this.handleCancel.bind(this)}>
                  取消
                </Button>
                <Button
                  className="ok-btn"
                  onClick={this.handleSubmit.bind(this)}
                  loading={this.state.loading}
                >
                  保存
                </Button>
              </div>
            </div>
          }
        />
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    ...state.routing
  };
}

export default Form.create()(connect(mapStateToProps)(ModifyQuestion));
